package com.itheima.reggie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.wxpay.sdk.WXPay;
import com.itheima.reggie.common.R;
import com.itheima.reggie.config.MyConfig;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public R sumbit(Orders orders) {
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");
        LambdaQueryWrapper<ShoppingCart> catwrapper = new LambdaQueryWrapper<>();
        catwrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(catwrapper);
        System.out.println(shoppingCarts);
        User user = userMapper.selectById(userId);
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        orders.setStatus(1);
        orders.setUserId(userId);
        orders.setAddress(addressBook.getDetail());
        orders.setAmount(sum(shoppingCarts));
        orders.setConsignee(addressBook.getConsignee());
        orders.setOrderTime(new Date());
        orders.setPayMethod(1);
        orders.setNumber(UUID.randomUUID().toString());
        orders.setPhone(addressBook.getPhone());
        orders.setUserName(user.getName());
        orders.setCheckoutTime(new Date());
        ordersMapper.insert(orders);
        String s = JSON.toJSONString(shoppingCarts);
        List<OrderDetail> orderDetails = JSON.parseArray(s, OrderDetail.class);
        orderDetails.stream().forEach(c -> {
            c.setOrderId(orders.getId());
        });
        for (OrderDetail orderDetail : orderDetails) {
            orderDetailMapper.insert(orderDetail);
        }
        LambdaUpdateWrapper<ShoppingCart> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        shoppingCartMapper.delete(wrapper);

        /**
         * url ：  /pay/unifiedorder    wxPay.unifiedOrder
         * 请求方式
         * 请求参数    requsetMap
         * 返回值      responseMap
         */
        //微信支付的测试接口
        //1.创建一个微信支付核心对象
        MyConfig my = new MyConfig();
        //CONFIG配置类
        WXPay wxPay = null;
        try {
            wxPay = new WXPay(my);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //3.可以进行微信支付接口的调用了
        //统一下单接口
        //4.wxPay.unifiedOrder(); = 调用微信的支付接口  参数map
        Map<String, String> requsetMap = new HashMap<>();
        //购买的商品信息
        requsetMap.put("body", "红烧肉盖浇饭");
        //商家的订单号
        requsetMap.put("out_trade_no", orders.getId() + "");
        //付款金额
        requsetMap.put("total_fee", "1");//以分为单位

        requsetMap.put("spbill_create_ip", "127.0.0.1");
        //回调通知  商家接收微信的信息的接口
        requsetMap.put("notify_url", "http://www.baidu.com");
        //支付类型
        requsetMap.put("trade_type", "NATIVE");

        //模拟浏览器发送一个http请求
        /**
         * requsetMap 代表请求参数
         * responseMap  返回值
         */
        Map<String, String> responseMap = null;
        try {
            responseMap = wxPay.unifiedOrder(requsetMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(responseMap);
        return R.success(responseMap);
        //返回值中 code_url 就是支付二维码连接

        /**
         * return_msg  代表成功
         * result_code SUCCESS
         * code_url   生成支付二维码  weixin://wxpay/bizpayurl?pr=23CaFbOzz, = 二维码
         *
         *
         * {nonce_str=IQ1juuH6JdbiJygc, code_url=weixin://wxpay/bizpayurl?pr=23CaFbOzz,
         * appid=wx8397f8696b538317,
         * sign=0BB8257245E8255C6D6176930516546398AB9A0F23A4F49D8D7B46078CF3B6EA,
         * trade_type=NATIVE, return_msg=OK, result_code=SUCCESS, mch_id=1473426802,
         * return_code=SUCCESS, prepay_id=wx10094200313158c49bc3946a2e6a7d0000}
         */


    }

    private BigDecimal sum(List<ShoppingCart> shoppingCarts) {
        BigDecimal bigDecimal = new BigDecimal(0);
        for (ShoppingCart shoppingCart : shoppingCarts) {
            bigDecimal = bigDecimal.add(shoppingCart.getAmount());
        }
        return bigDecimal;
    }

    @Override
    public R userPage(Integer page, Integer pageSize) {
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");
        IPage<Orders> p = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, userId);
        wrapper.orderByDesc(Orders::getCheckoutTime);
        IPage<Orders> pages = ordersMapper.selectPage(p, wrapper);
        return R.success(pages);
    }

    @Override
    public void updateState(String out_trade_no, String transaction_id) {
        Orders orders = ordersMapper.selectById(out_trade_no);
        orders.setStatus(2);
        orders.setNumber(transaction_id);
        ordersMapper.updateById(orders);
    }
}
